<template>
  <div class="passport-container">
    <div class="passport-form">
      <van-cell-group>
        <van-field
          ref="mobile"
          v-model="formData.mobile"
          required
          clearable
          label="手机号"
          placeholder="请输入手机号"
          :error-message="errorMsg.mobile"
        />
        <van-field
          ref="code"
          v-model="formData.code"
          center
          required
          clearable
          label="短信验证码"
          placeholder="请输入验证码"
          :error-message="errorMsg.code"
        >
          <van-button
            slot="button"
            size="small"
            :disabled="countdown > 0"
            @click="sendMobileCode"
            type="primary"
          >{{ countdown ? countdown + 's' : '发送验证码'}}</van-button>
        </van-field>
      </van-cell-group>
    </div>
    <div class="passport-action">
      <van-button
        size="large"
        block
        @click="onSubmit"
        :disabled="disableSubmit"
      >提交</van-button>
    </div>
    <!-- 地址选择 -->
    <van-popup
      v-model="showArea"
      position="bottom"
    >
      <van-area
        :area-list="areaList"
        @confirm="onAddressConfirm"
        @cancel="closePopupArea"
        :value="apply.areaCode"
      />
    </van-popup>
    <!-- 职业选择 -->
    <van-popup
      v-model="showOccupation"
      position="bottom"
      :overlay="true"
    >
      <van-picker
        show-toolbar
        title="职业"
        :columns="options.occupations"
        @cancel="closePopupOccupation"
        @confirm="onOccupationConfirm"
      />
    </van-popup>
    <!-- 学历选择 -->
    <van-popup
      v-model="showQualification"
      position="bottom"
      :overlay="true"
    >
      <van-picker
        show-toolbar
        title="学历"
        :columns="options.qualifications"
        @cancel="closePopupQualification"
        @confirm="onQualificationConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import validator from '../../common/validator'
import {
  Row,
  Col,
  Cell,
  Button,
  CellGroup,
  Field,
  Area,
  Icon,
  Image,
  Popup,
  Picker,
  Lazyload
} from 'vant'

export default {
  components: {
    [Row.name]: Row,
    [Col.name]: Col,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Area.name]: Area,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Image.name]: Image,
    [Picker.name]: Picker,
    Lazyload
  },

  data () {
    return {
      sms: '',
      countdown: 0,
      apply: {
        memberId: 0,
        mobile: '',
        code: ''
      },
      disableSubmit: false,
      errorMsg: {
        mobile: '',
        code: ''
      },
      rules: {
        mobile: [
          {
            validator: (rule, value, callBack) => {
              if (!value) {
                callBack('请输入手机号码')
              } else if (/^[1][3-9][0-9]{9}$/.test(value)) {
                callBack()
              } else {
                callBack('请输入正确的手机号码')
              }
            }
          }
        ],
        code: [{ required: true, message: '请输入验证码' }]
      }
    }
  },

  created () {
    this.apply.typeId = this.$route.params.id
    this.onLoad()
    // this.validator = validator(this.rules, this.apply)
  },
  watch: {
    formData: {
      handler (cv, ov) {
        cv['addressText'] = this.addressText
        this.validator = validator(this.rules, cv)
      },
      deep: true
    }
  },
  computed: {
    formData () {
      return this.apply
    },
    addressText () {
      var { province, city, district, areaCode } = this.apply
      if (areaCode) {
        var arr = [province, city, district]
        if (province && province === city) {
          arr.splice(1, 1)
        }
        return arr
          .filter(function (text) {
            return text
          })
          .join('/')
      }
      return ''
    }
  },

  methods: {
    onLoad () {
      this.axios
        .get('/member/apply')
        .then(response => {
          if (response.data) {
            this.apply = Object.assign({}, this.apply, response.data.fullData)
            console.log(this.apply)
            console.log(this.addressText)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    onSubmit () {
      console.log(this.formData)
      this.validate((errors, fields) => {
        if (errors) {
          if (fields.length > 0) {
            let first = fields.shift()
            console.log(first)
            this.$refs[first.field].focus()
          }
          console.log(this.errorMsg)
        } else {
          this.submit()
        }
        console.log(fields)
      })
    },
    submit () {
      this.disableSubmit = true
      this.axios
        .post('/member/apply/create', this.apply)
        .then(response => {
          if (response.data) {
            this.$router.replace({ name: 'member' })
          } else {
            this.$toast('提交失败~')
            this.disableSubmit = false
          }
        })
        .catch(error => {
          this.disableSubmit = false
          this.$toast(error)
        })
    },
    sendsms () {
      this.axios
        .post('/sms/captcha', {
          mobile: this.apply.mobile,
          scope: 'member'
        })
        .then(response => {
          if (response.data) {
            this.$toast('发送成功')
            this.countdown = 60
            this.countdownSubtract()
          } else {
            this.$toast('发送失败')
          }
        })
        .catch(error => {
          this.$toast(error)
        })
    },
    sendMobileCode () {
      this.validate(errors => {
        if (!errors) {
          this.sendsms()
        }
      }, 'mobile')
    },
    countdownSubtract () {
      if (this.countdown > 0) {
        setTimeout(() => {
          this.countdown -= 1
          this.countdownSubtract()
        }, 1000)
      }
    },
    /**
     * 清除验证提示
     * @param attrs
     */
    resetField (attrs) {
      attrs = !attrs
        ? Object.keys(this.errorMsg)
        : Array.isArray(attrs)
          ? attrs
          : [attrs]
      attrs.forEach(attr => {
        this.errorMsg[attr] = ''
      })
    },
    /**
     * 验证方法
     * @param callback
     * @param data
     */
    validate (callback, data) {
      this.validator.validate((errors, fields) => {
        this.resetField()
        if (errors) {
          fields.forEach(item => {
            this.errorMsg[item.field] = item.message
          })
        }
        callback && callback(errors, fields)
      }, data)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.passport-container {
  position: relative;
  overflow: hidden;
  width: 100%;
  min-height: 100%;
}

.passport-form {
  padding-top: 15px;
}
.van-cell-group {
  margin-bottom: 10px;
}
.passport-action {
  padding: 15px;
  width: 100%;

  .van-button--default {
    background-color: #e3c184;
    border-color: #e3c184;
    color: #805916;
    border-radius: 5px;
  }
}

.passport-notice {
  padding: 20px 15px;
  .van-cell {
    border-radius: 30px;
    background: #fcfaed;
    padding: 5px 10px;
    font-size: 12px;
    line-height: 24px;
    &__left-icon {
      color: #ff5544;
    }
    &__right-icon {
      color: #f1b249;
    }
    &__title {
      color: #6d511f;
    }
    &__value {
      color: #f1b249;
    }
  }
}
.passport-privilege {
  h1 {
    text-align: center;
    font-weight: 600;
    font-size: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #7d5609;
    small {
      font-weight: normal;
      opacity: 0.9;
    }
    &::before,
    &::after {
      content: "";
      width: 3px;
      height: 10px;
      background: #dfc087;
      margin: 0 10px;
      border-radius: 3px;
      transform: rotate(30deg);
    }
  }
  &-list {
    flex-wrap: wrap;
    padding: 5px;
    .van-col {
      padding: 10px 5px;
      text-align: center;
      font-weight: 300;
    }
  }
}
</style>
